﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Xml;
using ClientLib;

namespace TestApp
{
    public partial class Main : Form
    {
        ClientUtil _cutil;
        JsvcEnc.EncSoapXml xmlsvc;

        DataTable userMethods;

        public Main()
        {
            InitializeComponent();

            try
            {
                _cutil = new ClientUtil();

                txtServerURL.Text = ConfigurationManager.AppSettings["ServiceURL"].ToString();
                txtUserName.Text = ConfigurationManager.AppSettings["TestUserName"].ToString();
                txtPassword.Text = ConfigurationManager.AppSettings["TestPassword"].ToString();

                xmlsvc = new JsvcEnc.EncSoapXml();
                xmlsvc.Url = txtServerURL.Text;
            }
            catch (Exception ex)
            {
                ErrorUtil eutil = new ErrorUtil();
                eutil.LogException(_cutil.UserID, "Main Main", "", ex);
            }
        }

        // ********************************************************************
        // Connection Test Section
        // ********************************************************************

        # region Connection Test

        /// <summary>
        /// 
        /// </summary>
        protected void ResetMain()
        {
            try
            {
                // get public key, save to global variable
                _cutil.PublicKey = xmlsvc.GetPublicKey();

                // write public key to PublicKey control
                rtbPublicKey.Text = _cutil.PublicKey;

                // get server time and calculate offset
                string svrtimestr = xmlsvc.GetServerTime();
                string localtimestr = _cutil.GetTimeInMilliseconds();

                double servermillisec = Convert.ToDouble(svrtimestr);
                double localmillisec = Convert.ToDouble(localtimestr);

                _cutil.Offset = localmillisec - servermillisec;
 
                // write offset milliseconds to servertime control
                txtServerTime.Text = _cutil.Offset.ToString();

                // set sessionid value
                _cutil.SessionID = System.Guid.NewGuid().ToString();

                txtRequestTime.Text = "";
                txtStartTime.Text = "";
                txtEndTime.Text = "";
                txtResponseTime.Text = "";

                txtSendTime.Text = "";
                txtProcessTime.Text = "";
                txtReturnTime.Text = "";
                txtTotal.Text = "";

                txtRequestID.Text = "";
                rtbClearInput.Text = "";
                rtbEncryptInput.Text = "";
                rtbEncryptOutput.Text = "";
                rtbClearOutput.Text = "";
            }
            catch (Exception ex)
            {
                ErrorUtil eutil = new ErrorUtil();
                eutil.LogException(_cutil.UserID, "Main ResetMain", "", ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            ResetMain();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            string results = "";
            string encryptedinput = "";
            UIUtil uiutil = new UIUtil();

            try
            {
                if (txtUserName.Text.Length > 0 && txtPassword.Text.Length > 0)
                {
                    _cutil.UserName = txtUserName.Text;
                    _cutil.Password = txtPassword.Text;

                    // form XML from input values
                    Dictionary<string, string> paramList = new Dictionary<string, string>();
                    paramList.Add("EchoText", rtbEchoInput.Text);

                    EncryptUtil eutil = new EncryptUtil();
                    encryptedinput = _cutil.BuildMessageXML("Testing.EchoData.Base", paramList, true);

                    txtRequestID.Text = _cutil.RequestID;
                    rtbClearInput.Text = uiutil.FormatXML(_cutil.RequestMessage);

                    // write XML to EncryptInput control
                    rtbEncryptInput.Text = encryptedinput;

                    // make method call to web service
                    results = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput);
                    rtbEncryptOutput.Text = results;

                    // decrypt the web service results
                    string decryptedResults = eutil.DecryptString2(results, _cutil.SymmKey);
                    rtbClearOutput.Text = uiutil.FormatXML(decryptedResults);

                    // parse the decrypted results
                    _cutil.ParseResponseMessage(decryptedResults);

                    // display performance metrics
                    txtRequestTime.Text = _cutil.RequestTime;
                    txtStartTime.Text = _cutil.StartTime;
                    txtEndTime.Text = _cutil.EndTime;
                    txtResponseTime.Text = _cutil.ResponeTime;

                    txtSendTime.Text = (Convert.ToDouble(txtStartTime.Text) - Convert.ToDouble(txtRequestTime.Text)).ToString();
                    txtProcessTime.Text = (Convert.ToDouble(txtEndTime.Text) - Convert.ToDouble(txtStartTime.Text)).ToString();
                    txtReturnTime.Text = (Convert.ToDouble(txtResponseTime.Text) - Convert.ToDouble(txtEndTime.Text)).ToString();
                    txtTotal.Text = (Convert.ToDouble(txtResponseTime.Text) - Convert.ToDouble(txtRequestTime.Text)).ToString();

                    // allow methods to be tested
                    btnGetUserMethods.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                ErrorUtil eutil = new ErrorUtil();
                eutil.LogException(_cutil.UserID, "Main btnSend_Click", "", ex);
            }
        }

        // show the ConnectHelp form
        private void btnConnTestHelp_Click(object sender, EventArgs e)
        {
            frmConnectHelp connHelp = new frmConnectHelp();
            connHelp.Show();
        }

        # endregion

        

        // ********************************************************************
        // Method Tests Section
        // ********************************************************************

        # region Method Tests

        private void btnGetUserMethods_Click(object sender, EventArgs e)
        {
            // first, must call userlogin method to get userid
            Dictionary<string, string> paramList = new Dictionary<string, string>();

            string encryptedinput = _cutil.BuildMessageXML("SystemAdmin.UserLogin.Base", paramList, true);
            string results = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput);

            EncryptUtil eutil = new EncryptUtil();
            _cutil.ParseResponseMessage(eutil.DecryptString2(results, _cutil.SymmKey));

            if (_cutil.ResponseCode == "Success")
            {
                // set the userid value
                _cutil.UserID = _cutil.Result;

                // get all methods available to user, grouped by actiontype
                Dictionary<string, string> paramList2 = new Dictionary<string, string>();
                paramList2.Add("UserID", _cutil.UserID);

                string encryptedinput2 = _cutil.BuildMessageXML("Testing.GetUserMethods.Base", paramList2, true);
                string results2 = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput2);

                _cutil.ParseResponseMessage(eutil.DecryptString2(results2, _cutil.SymmKey));

                if (_cutil.ResponseCode == "Success")
                {
                    // populate the listbox with the method names
                    string tmpdata = _cutil.Result;
                    tmpdata = tmpdata.Replace("<![CDATA[", "");
                    tmpdata = tmpdata.Replace("]]>", "");

                    StringReader sr = new StringReader(tmpdata);
                    userMethods = new DataTable();
                    userMethods.ReadXml(sr);

                    if (userMethods.Rows.Count > 0)
                    {
                        btnRunTests.Enabled = true;

                        foreach (DataRow dr in userMethods.Rows)
                        {
                            lstUserMethods.Items.Add(dr["MethodName"].ToString());
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRunTests_Click(object sender, EventArgs e)
        {
            // build request message template



            // run all delete methods to clear data (not tracked)
            foreach (DataRow dr in userMethods.Rows)
            {
                
            }

            // run all insert methods
            foreach (DataRow dr in userMethods.Rows)
            {

            }

            // run all select methods
            foreach (DataRow dr in userMethods.Rows)
            {

            }

            // run all update methods
            foreach (DataRow dr in userMethods.Rows)
            {

            }

            // run all delete methods
            foreach (DataRow dr in userMethods.Rows)
            {

            }

        }


        # endregion

        // ********************************************************************
        // Test Results Section
        // ********************************************************************

        # region Test Results



        # endregion
    }
}
